package com.nxmu.dao.impl;

import com.nxmu.dao.Dao;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.io.Serializable;
import java.util.List;

public class BaseDao<T> implements Dao<T> {

//    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    public T findById(Class clazz ,Integer id) {
        return (T) this.getSession().get(clazz , id);
    }

    @Override
    public List<T> findAll(String hql) {
        return this.getSession().createQuery(hql).list();
    }

    @Override
    public List<T> findByHql(String hql, Object... objs) {
        Query query = this.getSession().createQuery(hql);
        setQueryParame(query,objs);
        return query.list();
    }

    @Override
    public boolean save(T t) {
        Serializable serializable = this.getSession().save(t);
        return serializable == null ? false : true;
    }

    @Override
    public void saveOrUpdate(T t){
        this.getSession().saveOrUpdate(t);
    }

    @Override
    public void deleteEntity(T t) {
        this.getSession().delete(t);
    }


    @Override
    public void deleteByHql(String hql, Object... objs) {
        Query query = getSession().createQuery(hql);
        setQueryParame(query,objs);
        query.executeUpdate();
    }

    @Override
    public void update(T t) {
        this.getSession().update(t);
    }

    /**
     * 为占位符赋值
     * @param query
     * @param objs
     */
    private void setQueryParame(Query query, Object[] objs) {
        for(int i = 0; i < objs.length; i++) {
            query.setParameter(i, objs[i]);
        }
    }

}
